



//
//  ZPayViewController.m
//  ZQLearn
//
//  Created by macfeel on 2019/5/8.
//  Copyright © 2019 macfeel. All rights reserved.
#import "ZAddressListViewController.h"
#import "ZAddressListViewController.h"
#import "XALoginAlertView.h"
#import "PPAlertView.h"
#import "LZActionSheet.h"
#import "ZPayViewController.h"
#import "OrderCell.h"
#import "OrderModel.h"
#import "PayHeadView.h"
#import "PayFootView.h"
#import "PayModel.h"
#import "IntegralBouncedView.h"

@interface ZPayViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,LZActionSheetDelegate,ZFActionSheetDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *addressArray;
@property (nonatomic,strong)PayHeadView *head;

@property (nonatomic,strong)PayFootView *foot;

@property (nonatomic,strong)XALoginAlertView *XAAlertView;

@property (nonatomic,strong)UITextField *textFd;
@property (nonatomic,strong)UILabel *payMoneyLab;

@property (nonatomic,copy)NSString *addressId;
///商品id
@property (nonatomic,copy)NSString *commodityId;

///积分可兑换的人民币（元）
@property (nonatomic,assign)NSInteger jifen;

///待支付的金额
@property (nonatomic,assign)NSInteger needPayMoney;


///选择积分抵扣后的金额
@property (nonatomic,copy)NSString *lastConfirmMoney;

///订单id
@property (nonatomic,copy)NSString *orderId;

@property (strong, nonatomic) IntegralBouncedView *bouncedView;

@end
//#define cellIdentifier @"order"
@implementation ZPayViewController
#define cellIdentifier @"order"
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 10, ScreenWidth , ScreenHeight - kTabHeight-ScreenHeightFlex) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 95.f;
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"OrderCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        WeakStament(ws);
        //        _tableView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
        //            [ws refreshData];
        //        }];
        //        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //            [ws loadMoreData];
        //        }];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    ///付款结算页面
    [self.navigationItem setItemWithTitle:@"结算" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    self.jifen = 0;
    self.needPayMoney = 0;
    self.dataArray = [NSMutableArray array];
    self.addressArray = [NSMutableArray array];
    //    [self showNoDataImageView:@"none" withTitle:@"暂无数据哦"];
    [self.view addSubview:self.tableView];
    self.head = [[[NSBundle mainBundle]loadNibNamed:@"PayHeadView" owner:self options:nil]lastObject];
    self.head.frame = CGRectMake(0, 0, ScreenWidth, 75);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHead)];
    [self.head addGestureRecognizer:tap];
    self.tableView.tableHeaderView = self.head;
    
    self.foot = [[[NSBundle mainBundle]loadNibNamed:@"PayFootView" owner:self options:nil]lastObject];
    self.foot.frame = CGRectMake(0, 0, ScreenWidth, 150);
    self.tableView.tableFooterView = self.foot;
    
    ///
    UIButton *cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cartBtn.frame = CGRectMake(0, ScreenHeight-45.f-64, ScreenWidth, 45.f);
    cartBtn.backgroundColor = [UIColor redColor];
    [cartBtn addTarget:self action:@selector(payAction:) forControlEvents:UIControlEventTouchUpInside];
    [cartBtn setTitle:@"去支付" forState:UIControlStateNormal];
    [self.view addSubview:cartBtn];
    
    ////请求地址信息
    [self loadUserAddress];
    
    //    ///配置收货信息
//    self.head.personLab.text = [NSString stringWithFormat:@"收货人: %@   %@",self.model.userAddressInfo[@"name"],self.model.userAddressInfo[@"phone"]];
//    NSString *address = [NSString stringWithFormat:@"收货地址: %@%@%@%@",self.model.userAddressInfo[@"province"],self.model.userAddressInfo[@"city"],self.model.userAddressInfo[@"area"],self.model.userAddressInfo[@"address"]];
//    self.head.addressLab.text = address;
    
    ////如果直接从商品详情进来的购买
    [self.dataArray removeAllObjects];
    if ([self.flag isEqualToString:@"cdetail"]) {
        if (self.storeModel) {
            
            ///拿到商品id,订单生成接口需要
            self.commodityId = self.storeModel.ID;
            
        }
        
        ///只有这一个
        [self.dataArray addObject:self.storeModel];
        
    }
    // Do any additional setup after loading the view.
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    self.foot.xiaojiLab.text = [NSString stringWithFormat:@"共%@件商品,小计:",self.model.commodityNumber?:@"1"];
    if ([self.flag isEqualToString:@"cdetail"]) {
        ///商品详情进来
        self.foot.jifenLab.text = [NSString stringWithFormat:@"%@积分",self.storeModel.integral];
        self.needPayMoney = [self.storeModel.integral integerValue]/100;
        YYLog(@"待：%ld",(long)self.needPayMoney);
        
    }else{
        
        ///订单待付款进来
        self.foot.jifenLab.text = [NSString stringWithFormat:@"%@00积分",[UserInfoSave shareInstance].integral];
        
    }
    
    self.foot.myScoreLab.text = [NSString stringWithFormat:@"我的积分:%@",[UserInfoSave shareInstance].integral];
    
}
///配置收货信息
-(void)setUIWithModel:(CommonModel *)model{
    
    if (model) {
        self.head.personLab.text = [NSString stringWithFormat:@"收货人: %@   %@",model.name,model.phone];
        NSString *address = [NSString stringWithFormat:@"收货地址: %@%@%@%@",model.province,model.city,model.area,model.address];
        self.head.addressLab.text = address;
    }else{
        ///添加收货信息
        self.head.personLab.hidden = YES;
        self.head.addressLab.hidden = YES;
        self.head.addAddressBtn.hidden = false;
        [self.head.addAddressBtn addTarget:self action:@selector(addAddress) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
}

///点击收货地址区域
-(void)tapHead{
    
    ZAddressListViewController *list = [ZAddressListViewController new];
    WeakStament(ws);
    
    list.block = ^(CommonModel * _Nonnull model) {
        YYLog(@"%@",model.name);
        [ws setUIWithModel:model];
    };
    [self.navigationController pushViewController:list animated:YES];
}
#pragma mark - 收货地址
///获取用户收货地址列表
-(void)loadUserAddress{
    
    NSDictionary *dict = @{@"pageIndex":@"1",@"pageSize":@"10",@"userInfo.id":[UserInfoSave shareInstance].uid?:@""};
    WeakStament(ws);
    [ZNetworkService postRequestWithBaseUrl:kAddressUrl setParameters:dict success:^(id result) {
        
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSArray *arr = result[@"result"];
            NSDictionary *dict = [arr firstObject];
            CommonModel *model = [CommonModel mj_objectWithKeyValues:dict];
            self.addressId = model.ID;
            YYLog(@"%@",self.addressId);
            ///就一个对象
            [ws setUIWithModel:model];
            //            [self.addressArray addObject:model];
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
}

-(void)addAddress{
    ZAddressListViewController *addlist = [ZAddressListViewController new];
    [self.navigationController pushViewController:addlist animated:YES];
}

///去支付
- (void)payAction:(UIButton *)btn
{
    
    ///点击去支付，首先要生成一个订单，然后获取到订单id
    ///这里用一个弹框弹出，表示订单生成成功
    [PPAlertView showWithTitle:@"温馨提示" message:@"确认支付" leftText:@"取消" rightText:@"确定" leftBlock:^{
        
    } rightBlock:^{
#pragma mark - 积分抵扣弹框
        self.bouncedView = [[IntegralBouncedView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        self.bouncedView.alpha = 0.0;
        
        //具体的价格
        self.bouncedView.amountLabel.text = self.strAmount;
        YYLog(@"%@",self.strAmount);
        self.bouncedView.strAmount = self.strAmount;
        YYLog(@"hhh%@",self.bouncedView.strAmount);
        UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
        [window addSubview:self.bouncedView];
        
        [UIView animateWithDuration:0.3 animations:^{
            self.bouncedView.alpha += 1.0;
        } completion:^(BOOL finished) {
            self.bouncedView.alpha = 1.0;
        }];
        WeakStament(ws);
        self.bouncedView.payBlock = ^(NSString * _Nonnull strAmount) {
            YYLog(@"------:%@",strAmount);
            [ws makeAnOrderWithMoney:strAmount];
            
        };
    }];

}


#pragma mark - 生成一个订单
///生成一个订单
-(void)makeAnOrderWithMoney:(NSString *)money{
    //这个接口的数据提交方式也是json 类似登录
    [UserModel shareInstance].isLogin = YES;
    //执行操作 进入支付流程 进行支付，首先要生成一个订单，所以首先要请求添加一个商品订单，然后拿到订单id
    NSString *userId = [UserInfoSave shareInstance].uid;
    NSArray *arr = @[@{@"commodityInfo":@{@"id":self.commodityId?:@""},@"commodityNumber":@"1"}];
    NSDictionary *dict =@{@"buyRecordsType":@"4",@"userInfo.id":userId,@"userInfo":@{@"id":userId},@"orderCommodityInfoList":arr,@"userAddressInfo":@{@"id":self.addressId},@"money":money,};
    
    [ZNetworkService postRequestWithBaseUrl:kAddStoreCommodityOrderUrl setParameters:dict success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"errorCode"] integerValue]==0) {
            //拿到订单号
            self.orderId = result[@"result"][@"id"];
            
            ///确认支付
            ZFActionSheet *sheet = [ZFActionSheet actionSheetWithTitle:nil confirms:@[@"微信支付",] cancel:@"取消" style:ZFActionSheetStyleDefault];
            sheet.delegate = self;
            [sheet show];
            
        }
        [UserModel shareInstance].isLogin = false;
    } fail:^(NSError *error) {
        [UserModel shareInstance].isLogin = false;
    } delegater:nil];
    
}

#pragma mark - textFd delegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField==self.textFd) {
        YYLog(@"%@",self.textFd.text);
        if ([self.textFd.text integerValue]<=self.jifen) {
            self.XAAlertView.payMoneyLab.text =[NSString stringWithFormat:@"%ld",(self.needPayMoney-[self.textFd.text integerValue])];
            self.lastConfirmMoney = self.XAAlertView.payMoneyLab.text;
            self.needPayMoney = [self.lastConfirmMoney integerValue];
            YYLog(@"hhello:%ld",self.needPayMoney);
            YYLog(@"%ld",self.needPayMoney);
            
        }else{
            self.textFd.text = [NSString stringWithFormat:@"%ld",self.jifen];
            return;
        }
        
    }
}


#pragma mark - alert delegate

////系统的 alertView 有bug  竟然被碰到了，恶心啊

#pragma mark  - ZFAction delegate  拿到订单id后进行支付
-(void)clickAction:(ZFActionSheet *)actionSheet atIndex:(NSUInteger)index{
    
    if (index==0) {
        //微信支付
        //type  1 商城里的商品  2 vip   3 图书视频等资源
        //paytype 1支付宝  2微信
        ///type 1商城商品  2vip  3电子书资源
        NSDictionary *dict = @{@"id":self.orderId?:@"",@"type":@"1",@"paytype":@"2",};
        [ZNetworkService postRequestWithBaseUrl:kCallPayUrl setParameters:dict success:^(id result) {
            YYLog(@"%@",result);
            if ([result[@"errorCode"]integerValue]==0) {
                NSDictionary *ddic = result[@"result"];
                PayModel *model = [PayModel mj_objectWithKeyValues:ddic];
                [PayModel  wxPay:model];
            }else{
                [AFToast showText:@"接口返回错误"];
            }
        } fail:^(NSError *error) {
            
        } delegater:nil];
        
    }else{
        //支付宝
       
    }
}


#pragma mark - datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([self.flag isEqualToString:@"cdetail"]) {
        return self.dataArray.count;
    }else{
        return self.model.orderCommodityInfoResponDTOList.count;
    }
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderCell *cell;
    
    if ([self.flag isEqualToString:@"cdetail"]) {
        //从商品详情点击购买进来
        StoreModel *model = [self.dataArray lastObject];
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        cell.nameLab.text = model.name;
        cell.jifenLab.text = [NSString stringWithFormat:@"%@积分",model.integral];
        cell.numLab.text =@"1";
        [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kStorePicServerUrl,model.photo]] placeholderImage:nil];
        return cell;
        
    }else{
        
        //从订单中的购买进来
        OrderModel *model = self.model.orderCommodityInfoResponDTOList[indexPath.row];
        //    OrderModel *subModel = model.orderCommodityInfoResponDTOList[indexPath.row];
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        cell.nameLab.text = model.commodityInfo[@"name"];
        cell.jifenLab.text = [NSString stringWithFormat:@"%@积分",model.commodityInfo[@"integral"]];
        cell.numLab.text =[NSString stringWithFormat:@"X%@",model.commodityNumber];
        [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kStorePicServerUrl,model.commodityInfo[@"photo"]]] placeholderImage:nil];
        return cell;
        
    }
    
    return nil;
}

#pragma mark - delegate
#define OrderSectionHeaderHeight 10
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return OrderSectionHeaderHeight;
    //如果设置section的header高度，不设置footer高度，footer默认等于header高度
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, OrderSectionHeaderHeight)];
    view.backgroundColor = kBackgroundColor;
    return view;
    
}


@end
